export default class Collction {
    /**指定Model类型 */
    Model = null

    collection = []

    constructor() {
        var options = arguments[0] || {};
        if (options.Model) {
            try {
                var instance = new options.Model();
                if (!this.isFunction(instance.assign))
                    throw new Error('传入的model不是集成自mode-base的model');
            } catch (err) {
                throw new Error('传入的model不是集成自mode-base的model');
            }

            this.Model = model;
        }
    }

    /**判断参数是不是函数 */
    isFunction(obj) {
        return Object.prototype.toString.call(obj) === '[object Function]';
    }

    /**判断参数是不是对象 */
    isObject(obj) {
        return Object.prototype.toString.call(obj) === '[object Object]';
    }

    /**判断参数是不是数组 */
    isArray(obj) {
        return Object.prototype.toString.call(obj) === '[object Array]';
    }

    /**把数据加到数组中 */
    add(model, options) {
        options = options || {};
        if (!(model instanceof this.Model))
            model = new this.Model().assign(model);

        this.collection.push(model);
    }

    /**删除 */
    destroy(model, options) {

        if (!model || !model.length) throw new Error('model不能为null或者数组长度不能等于0')
        var idField = this.Model.$config.id;
        var isArray = this.isArray(model);
        var vm = this;

        if (isArray) {
            /**批量删除数据 */
            var models = model;
            var idCollection = [];
            models.forEach(item => {
                if (options.silence) {
                    var match = vm.findById(item[idField]);
                    this.collection.splice(match.index, 1)
                } else {
                    var match = vm.findById(item[idField]);
                    idCollection.push(match.model[idField]);
                }
            });
        } else {
            /**单独删除数据 */

            var math = this.findById(model[idField]);
            if (math.index !== -1) {
                var vm = this;
                vm.collection.splice(match.index, 1)
            }
        }
    }

    /**批量更新数据 */
    update(models, options) {
        if (!model || !model.length) throw new Error('model不能为null或者数组长度不能等于0')
        var idField = this.Model.$config.id;
        var vm = this;

        var models = model;
        var data = [];
        models.forEach(item => {
            var match = vm.findById(item[idField]);
            data.push(match.model.convertPojo());
        });
    }
 
    /**返回数组对象 */
    toArray() { return this.collection }

    /**根据id找出数据 */
    findById(id) {
        var result = { model: null, index: -1 };
        this.collection.forEach((item, index) => {
            if (item[this.Model.$config.id].toString() === id.toString()) {
                result.model = item;
                result.index = index;
            }
        });

        return result;
    }
}